<template>
  <div class="payment-management">
    <h2>支付记录管理</h2>

    <!-- 查询条件 -->
    <el-form :inline="true" :model="searchObj" class="demo-form-inline" style="margin-top:10px">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchObj.goods_name" placeholder="请输入商品名称" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handlerSearch">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 支付记录表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="支付记录ID" width="120"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column prop="goods_name" label="商品名称" width="200"></el-table-column>
      <el-table-column prop="payway" label="支付方式" width="120"></el-table-column>
      <el-table-column prop="price" label="支付金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="pay_time" label="支付时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.pay_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button
              size="small"
              type="primary"
              @click="viewPaymentDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 支付详情弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="支付详情"
        width="500px"
    >
      <el-form label-width="100px" v-if="selectedPayment">
        <el-form-item label="支付记录ID：">
          <span>{{ selectedPayment.id }}</span>
        </el-form-item>
        <el-form-item label="用户名：">
          <span>{{ selectedPayment.username }}</span>
        </el-form-item>
        <el-form-item label="商品名称：">
          <span>{{ selectedPayment.goods_name }}</span>
        </el-form-item>
        <el-form-item label="支付方式：">
          <span>{{ selectedPayment.payway }}</span>
        </el-form-item>
        <el-form-item label="支付金额：">
          <span>¥{{ selectedPayment.price }}</span>
        </el-form-item>
        <el-form-item label="支付时间：">
          <span>{{ formatDateTime(selectedPayment.pay_time) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import paymentApi from '@/api/payment_api.js'
import goodsApi from '@/api/goods_api.js'
import userApi from '@/api/user_api.js'

// 表格数据
const tableData = ref([])
const total = ref(0)

// 查询条件
const searchObj = ref({
  current: 1,
  limit: 10,
  username: '',
  goods_name: ''
})

// 详情弹窗相关
const detailDialogVisible = ref(false)
const selectedPayment = ref(null)

// 页面加载完成后查询数据
onMounted(() => {
  search()
})

// 查询支付记录列表
const search = async () => {
  try {
    // 处理查询参数
    const queryParams = {};

    // 如果有用户名查询条件，先查询用户ID
    if (searchObj.value.username) {
      try {
        // 使用用户分页接口查找用户
        const userResult = await userApi.getUserPage(1, 100, { username: searchObj.value.username });
        console.log('用户查询结果:', userResult);
        if (userResult && userResult.records && userResult.records.length > 0) {
          // 找到匹配的用户，使用第一个匹配用户的ID进行查询
          queryParams.user_id = userResult.records[0].id;
        } else {
          // 没有找到匹配的用户，设置一个不可能存在的用户ID
          queryParams.user_id = -1;
        }
      } catch (error) {
        console.error('查询用户信息失败:', error);
        ElMessage.error("查询用户信息失败");
      }
    }

    // 如果有商品名称查询条件，先查询商品ID
    if (searchObj.value.goods_name) {
      try {
        // 使用商品分页接口查找商品
        const goodsResult = await goodsApi.getGoodsPage(1, 100, { name: searchObj.value.goods_name });
        console.log('商品查询结果:', goodsResult);
        if (goodsResult && goodsResult.records && goodsResult.records.length > 0) {
          // 找到匹配的商品，使用第一个匹配商品的ID进行查询
          queryParams.goods_id = goodsResult.records[0].id;
        } else {
          // 没有找到匹配的商品，设置一个不可能存在的商品ID
          queryParams.goods_id = -1;
        }
      } catch (error) {
        console.error('查询商品信息失败:', error);
        ElMessage.error("查询商品信息失败");
      }
    }

    console.log('发送的查询参数:', queryParams);
    const result = await paymentApi.getPaymentPage(queryParams, searchObj.value.current, searchObj.value.limit);
    console.log('支付记录查询结果:', result);

    // 处理支付记录数据，获取商品名称和用户名
    if (result.records) {
      // 先处理所有记录获取用户名
      const userIds = [...new Set(result.records.map(r => r.user_id).filter(id => id))];
      const userMap = {};

      // 批量获取用户信息
      for (const userId of userIds) {
        try {
          const userResult = await userApi.getUserById(userId);
          if (userResult && userResult.username) {
            userMap[userId] = userResult.username;
          }
        } catch (error) {
          console.error(`获取用户${userId}信息失败:`, error);
        }
      }

      // 处理每条记录
      for (let i = 0; i < result.records.length; i++) {
        const payment = result.records[i];

        // 设置用户名
        if (payment.user_id && userMap[payment.user_id]) {
          payment.username = userMap[payment.user_id];
        }

        // 获取商品名称
        if (!payment.goods_name && payment.goods_id) {
          try {
            const goodsResult = await goodsApi.getGoodsById(payment.goods_id);
            if (goodsResult && goodsResult.name) {
              payment.goods_name = goodsResult.name;
            } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
              payment.goods_name = goodsResult.data.name;
            }
          } catch (error) {
            console.error('获取商品信息失败:', error);
          }
        } else if (!payment.goods_name && payment.seckill_goods_id) {
          try {
            const goodsResult = await goodsApi.getGoodsById(payment.seckill_goods_id);
            if (goodsResult && goodsResult.name) {
              payment.goods_name = goodsResult.name;
            } else if (goodsResult && goodsResult.data && goodsResult.data.name) {
              payment.goods_name = goodsResult.data.name;
            }
          } catch (error) {
            console.error('获取秒杀商品信息失败:', error);
          }
        }
      }
    }

    tableData.value = result.records || []
    total.value = result.total || 0
  } catch (error) {
    console.error('查询支付记录列表时出错:', error)
    ElMessage.error("查询支付记录列表失败: " + (error.message || "未知错误"))
    tableData.value = []
    total.value = 0
  }
}

// 重置查询条件
const resetSearch = () => {
  searchObj.value.username = ''
  searchObj.value.goods_name = ''
  searchObj.value.current = 1
  search()
}

// 分页大小改变
const handleSizeChange = () => {
  search()
}

// 当前页改变
const handleCurrentChange = () => {
  search()
}

// 处理查询
const handlerSearch = () => {
  searchObj.value.current = 1
  search()
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    // 创建Date对象，自动处理时区
    const date = new Date(dateTimeStr)

    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return dateTimeStr.replace('T', ' ')
    }

    // 格式化为"YYYY-MM-DD HH:mm:ss"格式
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('日期格式化错误:', error)
    return dateTimeStr.replace('T', ' ')
  }
}

// 查看支付详情
const viewPaymentDetail = (row) => {
  selectedPayment.value = { ...row }
  detailDialogVisible.value = true
}
</script>

<style scoped>
.payment-management {
  padding: 20px;
  background-color: #fff;
}

.payment-management h2 {
  margin-bottom: 20px;
}

.demo-form-inline {
  margin-bottom: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
